<template>
	<div class="box">
    <!-- 左侧进度 -->
    <div class="left" :class="{ close: isFold === true }">
      <div class="content">
        <div class="left-top">{{extraData}}</div>
        <div class="shipData">
          <water-polo :data="waterPoloData"></water-polo>
        </div>
        <div class="panel">
          <panel :data="panelData"></panel>
        </div>
        <div class="step">
          <el-steps direction="vertical" :active="stepActive" process-status="wait">
            <el-step :title="item.title + ' ' + item.dynamicTime" v-for="item in statusData" :key="item.dynamicTypeCode">
              <i class="step_circle" slot="icon"></i>
            </el-step>
          </el-steps>
        </div>
      </div>
      <div class="fold-wrap">
				<div class="btn-fold" @click="foldNav">
					<!-- <i class="el-icon-caret-left"></i> -->
					<!-- <img width="16px" :src="isFold?require('../../../assets/svg/open.svg'):require('../../../assets/svg/close.svg')"> -->
					<img width="10px" :src="!isFold ? require('../../../assets/img/open.png') : require('../../../assets/img/close.png')" />
				</div>
			</div>
    </div>
    <!-- 右侧 -->
    <div class="right">
    <!-- 头部搜索模块 -->
		<headerSearch 
      :selectObj="selectObject" 
      :endSelect="endSelect"
      :goSearchFc="searchClick" 
      :buttonList="buttonList"
      @handleChange="handleChange"
      ref="headerSearch"
    />
		<!-- 中间表格模块 -->
    <el-tabs v-model="activeName" @tab-click="handleAcitveClick" type="border-card" style="box-shadow:none;border:none">
      <el-tab-pane label="预到" name="first">
        <BaseTable
          :data="cargotableData"
          :columns="cargotableDataColumns"
          :tableHeight="tableHeight"
          :pagination="false"
          :loading="loading"
          @details="tableClick"
        ></BaseTable>
      </el-tab-pane>
      <el-tab-pane label="锚地" name="second">
        <BaseTable
          :data="cargotableData"
          :columns="cargotableDataColumns"
          :tableHeight="tableHeight"
          :pagination="false"
          :loading="loading"
          @details="tableClick"
        ></BaseTable>
      </el-tab-pane>
      <el-tab-pane label="在港" name="third">
        <BaseTable
          :data="cargotableData"
          :columns="cargotableDataColumns"
          :tableHeight="tableHeight"
          :pagination="false"
          :loading="loading"
          @details="tableClick"
        ></BaseTable>
      </el-tab-pane>
      <el-tab-pane label="离泊" name="fourth">
        <BaseTable
          :data="cargotableData"
          :columns="cargotableDataColumns"
          :tableHeight="tableHeight"
          :pagination="false"
          :loading="loading"
          @details="tableClick"
        ></BaseTable>
      </el-tab-pane>
    </el-tabs>
		<div class="page">
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryAll.startpage"
				:page-sizes="[10, 15, 20, 25, 30]"
				:page-size="queryAll.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalNum"
			></el-pagination>
		</div>
    </div>

		<!-- 查看详细船舶数据 -->
		<el-drawer
			:before-close="handleClose"
			title="船舶数据"
			:visible.sync="drawerInner"
			direction="rtl"
			size="50%"
		>
      <detail 
        :descriptionsData="descriptionsData"
        :shipData="shipData"
        :berthSelectData="berthSelectData"
        ref="boatBerth"
        @closeDrawer="drawerInner = false"
      />
			<div class="demo-drawer__footer">
        <el-button size="mini" @click="drawerInner = false">取消</el-button>
			</div>
		</el-drawer>

    <!-- 查看船舶动态 -->
		<el-drawer
			:before-close="handleClose"
			title="船舶动态"
			:visible.sync="boatDynamic"
			direction="rtl"
			size="70%"
		>
      <BaseTable
        :data="boatDynamicData"
        :columns="boatDynamicDataColumns"
        :tableHeight="tableHeight"
        :pagination="false"
        :loading="loading"
      ></BaseTable>
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="boatDynamic = false" size="mini">确 定
				</el-button>
        <el-button size="mini" @click="boatDynamic = false">取消</el-button>
			</div>
		</el-drawer>

    <!-- 查看靠离泊计划 -->
		<el-drawer
			:before-close="handleClose"
			title="靠离泊计划"
			:visible.sync="berthing"
			direction="rtl"
			size="70%"
		>
      <div style="padding: 10px;color: #666;">
        <span style="margin-right:10px;">选择日期：</span>
        <el-date-picker
          v-model="berthingDate"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          size="mini">
        </el-date-picker>
        <span style="margin:0 10px;">选择时段：</span>
          <el-select v-model="berthingTimeArr" placeholder="请选择时段" size="mini">
            <el-option :label="'0900-1300'" :value="['09:00','13:00']"></el-option>
            <el-option :label="'1300-1700'" :value="['13:00','17:00']"></el-option>
            <el-option :label="'1700-2100'" :value="['17:00','21:00']"></el-option>
            <el-option :label="'2100-0900'" :value="['21:00','09:00']"></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="searchBerthing" style="margin:0 10px">查询</el-button>
          <el-button type="primary" size="mini" @click.stop="exportBerth">导出</el-button>
      </div>
      
      <BaseTable
        :data="berthingData"
        :columns="berthingDataColumns"
        :tableHeight="tableHeight"
        :pagination="false"
        :loading="loadingB"
      ></BaseTable>
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="berthing = false" size="mini">确 定
				</el-button>
        <el-button size="mini" @click="berthing = false">取消</el-button>
			</div>
		</el-drawer>

    <!-- 查看动态跟踪 -->
		<el-drawer
			:before-close="handleClose"
			title="动态跟踪"
			:visible.sync="dynamicTracking"
			direction="rtl"
			size="50%"
		>
      <dynamicTracking 
        :berthSelectData="berthSelectData"
        :clickRow="clickRow"
        :dynamicType="dynamicType"
        ref="dynamicTracking"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="saveDynamic" size="mini">保 存</el-button>
        <el-button size="mini" @click="dynamicTracking = false">取消</el-button>
			</div>
		</el-drawer>
	</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Dispatch/boatDispatch'
import headerSearch from '@/components/headerSearch'
import detail from './detail.vue'
import dynamicTracking from './dynamicTracking.vue' // 引入动态跟踪
import waterPolo from './waterPolo.vue' // 引入echarts图表
import panel from './panel.vue' // 引入echarts图表
import publicapi from '@/api/public'
import XLSX from 'xlsx';

export default {
  name: 'boatDispatching',
  components: {
    BaseTable,
    headerSearch,
    detail,
    dynamicTracking,
    waterPolo,
    panel
  },
  data() {
    return {
      extraData: '预到0 锚地0 在港0', // 合计
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageId',
          selectData: [],
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageId'
        },
        {
          name: '船代',
          type: 'select',
          modelName: 'customerId',
          selectValue: 'customerId',
          selectLabel: 'customerName',
          selectData: []
        }
      ],
      endSelect: [
        {
          name: '动态跟踪',
          type: 'select',
          modelName: 'dynamiTracking',
          selectValue: 'dictValue',
          selectLabel: 'dictLabel',
          selectData: [
            { dictLabel: '抵锚', dictValue: '3', disabled: true },
            { dictLabel: '起锚', dictValue: '4', disabled: true },
            { dictLabel: '靠泊', dictValue: '5', disabled: true },
            { dictLabel: '移泊', dictValue: '10', disabled: true },
            { dictLabel: '开工', dictValue: '6', disabled: true },
            { dictLabel: '停工', dictValue: '7', disabled: true },
            { dictLabel: '复工', dictValue: '8', disabled: true },
            { dictLabel: '完工', dictValue: '9', disabled: true },
            { dictLabel: '离泊', dictValue: '11', disabled: true }
          ]
        }
      ],
      // header的按钮list
      buttonList: [
        { label: '船舶动态', type: 'primary', icon: 'el-icon-s-flag', disabled: true, click: () => this.getBoatDynamic, permission: 'dispatchManagement:boatDispatching:getShipDynamicById' },
        { label: '靠离计划', type: 'primary', icon: 'el-icon-date', disabled: false, click: () => this.getBerthing, permission: 'dispatchManagement:boatDispatching:getInoutPlan' }
      ],
      cargotableData: [],
      cargotableDataColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次', render: (h, params) => {
          return h(
            'div',
            [
              h('span', {
                props: {
                  size: 'mini'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  innerHTML:
											`<span style='color:#0B6CD6;cursor:pointer'><span  style='padding-left:5px;'>${params.row.shipvoyageName}</span></span>`
                },
                on: {
                  click: () => {
                    this.getDetail(params.row)
                  }
                }
              })
            ]
          )
        } },
        { prop: 'customerName', label: '船代', isShort: true },
        { prop: 'cargoCategoryName', label: '货名' },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'weightTon', label: '载重吨' },
        { prop: 'arrivalTimePlan', label: '预抵日期', width: 130 },
        { prop: 'berthNo', label: '泊位' },
        { prop: 'groupBerthTime', label: '计划/实际靠泊' },
        { prop: 'groupPortName', label: '起运港/目的港' },
        { prop: 'loadUnload', label: '装卸' },
        { prop: 'statusName', label: '状态' }

      ],
      stepActive: 0,
      statusData: [
        { title: '预报', dynamicTypeCode: '1', dynamicTime: '' },
        { title: '确报', dynamicTypeCode: '2', dynamicTime: '' },
        { title: '抵锚', dynamicTypeCode: '3', dynamicTime: '' },
        { title: '起锚', dynamicTypeCode: '4', dynamicTime: '' },
        { title: '靠泊', dynamicTypeCode: '5', dynamicTime: '' },
        { title: '离泊', dynamicTypeCode: '6', dynamicTime: '' }
      ],
      drawerInner: false, // 船详细信息drawer
      descriptionsData: [ // 船描述信息字段
        [
          { label: '中文船名', prop: 'shipName' },
          { label: '英文船名', prop: 'shipNameEn' },
          { label: '船舶国籍', prop: 'nationName' },
          { label: '船舶类型', prop: 'shipTypeName' },
          { label: '长度', prop: 'shipLength' },
          { label: '船宽', prop: 'shipWidth' },
          { label: '总高度', prop: 'shipHeight' },
          { label: '型深', prop: 'mouldedDepth' },
          { label: '舱口数', prop: 'hatchNo' },
          { label: '总吨', prop: 'totalTon' },
          { label: '净吨', prop: 'netTon' },
          { label: '载重吨', prop: 'weightTon' },
          { label: 'IMO', prop: 'imo' },
          { label: 'MMSI', prop: 'mmsi' },
          { label: '呼号', prop: 'callNo' }
        ],
        [
          { label: '预抵时间', prop: 'arrivalTimePlan' },
          { label: '船代', prop: 'customerName' },
          { label: '航次', prop: 'voyage' },
          { label: '装卸', prop: 'loadUnload' },
          { label: '货种', prop: 'cargoCategoryName' },
          { label: '贸别', prop: 'tradeType' },
          { label: '抵港艏吃水', prop: 'bowDraft' },
          { label: '抵港艉吃水', prop: 'sternDraft' },
          { label: '拖轮', prop: 'reqTug' },
          { label: '拖轮个数', prop: 'tugNumber' },
          { label: '引航', prop: 'pilotage' },
          { label: '半载', prop: 'halfLoad' },
          { label: '起运港', prop: 'startPortName' },
          { label: '上一港', prop: 'prePortName' },
          { label: '下一港', prop: 'nextPortName' },
          { label: '目的港', prop: 'endPortName' },
          { label: '船上电话', prop: 'shipPhone' },
          { label: '附件', prop: 'callNo', span: 3 },
          { label: '备注', prop: 'remark', span: 4 }
        ]

      ],
      shipData: [ // 船描述信息对应数据
        {
          'createBy': null,
          'createName': null,
          'createTime': null,
          'updateBy': null,
          'updateName': null,
          'updateTime': null,
          'approvalBy': null,
          'approvalName': null,
          'approvalTime': null,
          'id': null,
          'sid': null,
          'shipName': null,
          'shipNameEn': null,
          'nationCode': null,
          'nationName': null,
          'shipTypeCode': null,
          'shipTypeName': null,
          'shipLength': null,
          'shipWidth': null,
          'mouldedDepth': null,
          'totalTon': null,
          'netTon': null,
          'weightTon': null,
          'hatchNo': null,
          'callNo': null,
          'imo': null,
          'mmsi': null,
          'remark': null,
          'status': null,
          'delFlag': null
        },
        {
          'createBy': null,
          'createName': null,
          'createTime': null,
          'updateBy': null,
          'updateName': null,
          'updateTime': null,
          'approvalBy': null,
          'approvalName': null,
          'approvalTime': null,
          'id': null,
          'shipId': null,
          'shipName': null,
          'voyage': null,
          'companyId': null,
          'companyName': null,
          'cargoCategoryCode': null,
          'cargoCategoryName': null,
          'tradeType': null,
          'loadUnload': null,
          'customerCode': null,
          'customerName': null,
          'startPortCode': null,
          'startPortName': null,
          'endPortCode': null,
          'endPortName': null,
          'prePortCode': null,
          'prePortName': null,
          'nextPortCode': null,
          'nextPortName': null,
          'shipPhone': null,
          'bowDraft': null,
          'sternDraft': null,
          'reqTug': null,
          'tugNumber': null,
          'halfLoad': null,
          'actualLoad': null,
          'pilotage': null,
          'arrivalTimePlan': null,
          'arrivalAnchorageTime': null,
          'leaveAnchorageTime': null,
          'berthTime': null,
          'berthId': null,
          'berthNo': null,
          'berthType': null,
          'bollardNoStart': null,
          'bollardNoEnd': null,
          'workStartTime': null,
          'workEndTime': null,
          'leaveBerthTime': null,
          'status': null,
          'receiveBy': null,
          'receiveByName': null,
          'receiveTime': null,
          'settlementStatus': null,
          'confirmBy': null,
          'confirmByName': null,
          'confirmTime': null,
          'delFlag': null,
          'delRemark': null,
          'remark': null,
          'assistWork': null,
          'shipLength': null,
          'shipWidth': null,
          'hatchNo': null,
          'totalTon': null,
          'netTon': null,
          'weightTon': null,
          'attachmentInfoList': null
        }
      ],
      detailFormData: {}, // 详细信息初始form
      boatDynamic: false, // 打开船舶动态drawer
      boatDynamicData: [], // 船舶动态表格数据
      boatDynamicDataColumns: [
        { prop: 'dynamicTypeName', label: '动态类型' },
        { prop: 'dynamicTime', label: '动态时间' },
        { prop: 'berthNo', label: '泊位' },
        { prop: 'berthType', label: '舷靠' },
        { prop: 'stopName', label: '停工原因' },
        { prop: 'remark', label: '备注' },
        { prop: 'bollardNoStart', label: '首榄编号', width: 90 },
        { prop: 'bollardNoEnd', label: '尾榄编号', width: 90 },
        { prop: 'stopTypeName', label: '停时类型名称' },
        { prop: 'createName', label: '操作人' },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 100,
          render: (h, params) => {
            const _this = this
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.index !== _this.boatDynamicData.length - 1
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    // innerHTML: `<i class="iconfont icon-tubiao_liebiaoshanchu" style="color:#DA2821"></i> 删除`
                    innerHTML: `<span style='color:#F75E5E'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ], // 船舶动态表格表头
      dynamicTracking: false, // 动态跟踪drawer
      dynamicType: '', // 动态跟踪的类型（停工开工..）
      dynamicFormData: { stopTypeCode: '', stopName: '', 'beforeBerthNo': '', 'dynamicTypeName': '', 'dynamicTypeCode': '', 'shipvoyageId': '', 'berthType': '', 'berthNo': '', 'berthId': '', 'bollardNoStart': '', 'bollardNoEnd': '', 'remark': '', 'dynamicTime': '' }, // 动态跟踪from
      berthing: false, // 靠离泊drawer
      berthingDate: '', // 靠离泊日期
      berthingTimeArr: [], // 靠离泊时段
      berthingData: [],
      berthSelectData: [], // 泊位下拉框数据
      berthingDataColumns: [
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'shipNameEn', label: '英文船名' },
        { prop: 'groupBerthTime', label: '靠离泊时间' },
        { prop: 'berthNo', label: '靠离泊位' },
        { prop: 'tugNumber', label: '拖轮数量' },
        { prop: 'cargoCategoryName', label: '货种' },
        { prop: 'shipLengthWidth', label: '总长/船宽' },
        { prop: 'loadWeight', label: '载货量/载重量' },
        { prop: 'customerName', label: '代理' },
        { prop: 'groupDraft', label: '吃水' },
        { prop: 'groupPilotage', label: '是否需引航' }
      ],
      activeName: 'first',
      loading: false,
      loadingB: false,
      clickRow: {},
      queryAll: {
        startpage: 1,
        pagesize: 10,
        activeName: 'first',
        portName: '',
        logogram: ''
      },
      totalNum: 0,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      isFold: false, // 是否折叠左侧信息,
      waterPoloData: { 'efficiency': '41.910', 'progress': '0.522', 'weight': '18817.380', 'finishWorkDate': '2023-02-17 08:00:00', 'startWorkDate': '2023-02-15 20:50:00' }, // echarts图表数据
      panelData: { 'efficiency': '41.910', 'progress': '0.522', 'weight': '18817.380', 'finishWorkDate': '2023-02-17 08:00:00', 'startWorkDate': '2023-02-15 20:50:00' }

    }
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight - 40
    }
  },
  watch: {
    dynamicTracking(newV) {
      if (!newV) {
        this.$refs.headerSearch.searchData.dynamiTracking = ''
      }
    }
  },
  created() {
    this.getBerthSelect()
    this.getCustomer()
    this.getShipvoyage()
  },
  methods: {
    /**
     * 获取船舶调度数据
     */
    async getBoatDispatchList() {
      this.loading = true
      await api
        .reqGetBoat(this.queryAll)
        .then(res => {
          this.loading = false
          this.buttonList[0].disabled = true
          this.cargotableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
          this.extraData = res.data.data.extraData
        })
        .catch(() => {})
    },
    /**
     * 获取点击行数据,获取船舶动态
     */
    async tableClick(row) {
      this.clickRow = row
      this.buttonList[0].disabled = false
      this.getBoatStatus(row) // 根据点击行获取动态跟踪是否可选中
      // 重置状态数据
      this.statusData.forEach(item => {
        item.dynamicTime = ''
      })
      this.stepActive = 0
      // 获取新状态
      const params = { shipvoyageId: row.id }
      const res = await api.reqGetBoatStatus(params) // 获取船动态
      this.boatDynamicData = res.data.data
      if (this.boatDynamicData.length === 0) return
      this.boatDynamicData.forEach(item => {
        this.statusData.forEach((i, index) => {
          if (item.dynamicTypeName === i.title) {
            i.dynamicTime = item.dynamicTime
            this.stepActive = Math.max(index + 1, this.stepActive)
          }
        })
      })
    },
    /**
     * 修改折叠状态
     */
    foldNav() {
      this.isFold = !this.isFold
    },
    /**
     * 根据选中数据的状态来修改动态跟踪的是否可选中
     */
    getBoatStatus(row) {
      this.endSelect[0].selectData.forEach(item => {
        item.disabled = true
      })
      if (row.statusName === '确报') {
        this.endSelect[0].selectData[0].disabled = false
        this.endSelect[0].selectData[2].disabled = false
      } else if (row.statusName === '抵锚') {
        this.endSelect[0].selectData[1].disabled = false
      } else if (row.statusName === '起锚') {
        this.endSelect[0].selectData[2].disabled = false
      } else if (row.statusName === '靠泊') {
        this.endSelect[0].selectData[3].disabled = false
        this.endSelect[0].selectData[4].disabled = false
      } else if (row.statusName === '开工' || row.statusName === '复工') {
        this.endSelect[0].selectData[5].disabled = false
        this.endSelect[0].selectData[7].disabled = false
      } else if (row.statusName === '停工') {
        this.endSelect[0].selectData[6].disabled = false
        this.endSelect[0].selectData[3].disabled = false
      } else if (row.statusName === '完工') {
        this.endSelect[0].selectData[8].disabled = false
      }
    },
    /**
     * 获取船代信息
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.selectObject[1].selectData = res.data.data
    },
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.selectObject[0].selectData = res.data.data
    },
    /**
     * 点击首列获取详细信息
     */
    async getDetail(row) {
      this.drawerInner = true
      const resDetail = await api.reqGetBoatDetail({ id: row.shipId }) // 获取船信息
      this.shipData[0] = resDetail.data.data
      const res = await publicapi.getShipVoyageById({ id: row.id }) // 获取航次信息
      this.shipData[1] = res.data.data
      const resBerthing = await api.reqGetBerthing({ shipvoyageId: row.id })
      this.$nextTick(() => {
        this.$refs.boatBerth.formData = resBerthing.data.data
        this.$refs.boatBerth.formData.shipvoyageId = row.id
        this.detailFormData = JSON.parse(JSON.stringify(resBerthing.data.data))
      })
    },
    /**
     * 获取泊位下拉选项
     */
    async getBerthSelect() {
      const res = await publicapi.queryberthbytype('')
      this.berthSelectData = res.data.data
    },
    /**
     * 获取船舶动态，打开drawer
     */
    async getBoatDynamic() {
      if (Object.keys(this.clickRow).length === 0) {
        this.$message.warning('请选择一条数据')
      } else {
        this.boatDynamic = true
      }
    },
    /**
     * 船舶动态的删除功能
     */
    async handleDelete(row) {
      this.$confirm('此操作将删除该船舶动态,是否确认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDeleteShipDynamic({ id: row.id }).then(res => {
          if (res.data.code === '0000') {
            this.boatDynamic = false
            this.$message.success('删除成功')
            this.getBoatDispatchList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
     * 动态追踪打开drawer
     */
    handleChange(i, data) {
      this.dynamicTracking = true
      this.dynamicType = i
      let dynamicTypeName = ''
      data.forEach(item => {
        if (item.dictValue === i) {
          dynamicTypeName = item.dictLabel
        }
      })
      this.$nextTick(() => {
        const object = this.$refs.dynamicTracking.formData
        for (const key in object) {
          object[key] = ''
        }
        this.$refs.dynamicTracking.formData.dynamicTypeName = dynamicTypeName
        this.$refs.dynamicTracking.formData.dynamicTypeCode = i
        this.$refs.dynamicTracking.formData.shipvoyageId = this.clickRow.id
        this.$refs.dynamicTracking.formData.beforeBerthNo = this.clickRow.berthNo
        this.$refs.dynamicTracking.formData.berthType = this.clickRow.berthType
      })
    },
    /**
     * 动态追踪内容保存
     */
    async saveDynamic() {
      this.$refs.dynamicTracking.$refs.ruleForm.validate((valid) => {
        if (valid) {
          api.reqAddShipDynamic(this.$refs.dynamicTracking.formData).then(res => {
            if (res.data.code === '0000') {
              this.dynamicTracking = false
              this.$message.success('新增成功')
              this.getBoatDispatchList()
              this.$refs.dynamiTracking.$refs.ruleForm.resetFields()
            }
          })
        } else {
          this.$message.warning('请完善表单')
          return false;
        }
      });
    },
    /**
     * 打开靠离泊计划，打开drawer
     */
    getBerthing() {
      this.berthing = true
      this.berthingDate = ''
      this.berthingTimeArr = []
    },
    /**
     * 靠离泊计划查询
     */
    async searchBerthing() {
      if (this.berthingDate === '' || this.berthingDate === null) {
        this.$message.warning('请选择日期！')
        return
      } else if (this.berthingTimeArr.length === 0) {
        this.$message.warning('请选择时段！')
        return
      }

      const startTime = this.berthingDate + ' ' + this.berthingTimeArr[0]
      const endTime = (this.berthingTimeArr[0] === '21:00' ? this.getNextDate(this.berthingDate) : this.berthingDate) + ' ' + this.berthingTimeArr[1]
      const params = { startTime, endTime }
      this.loadingB = true
      const res = await api.reqGetAllBerthing(params)
      this.berthingData = res.data.data
      this.loadingB = false
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getBoatDispatchList()
    },
    /**
     * 导出靠离泊计划
     */
    exportBerth() {
      const data = []
      this.berthingData.forEach(item => {
        const dataObj = {}
        this.berthingDataColumns.forEach(i => {
          const key = i.label
          const obj = { [key]: item[i.prop] }
          Object.assign(dataObj, obj)
        })
        data.push(dataObj)
      })
      console.log(data, 'data');
      var sheet1 = XLSX.utils.json_to_sheet(data)
      const cols = [
        { wch: 20 },
        { wch: 20 },
        { wch: 15 },
        { wch: 20 },
        { wch: 15 },
        { wch: 15 },
        { wch: 15 },
        { wch: 20 },
        { wch: 40 },
        { wch: 15 },
        { wch: 15 }
      ]
      sheet1['!cols'] = cols
      // 创建一个新的空的workbook
      var wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, sheet1, '靠离泊计划表')
      const workbookBlob = this.workbook2blob(wb)
      this.openDownloadDialog(workbookBlob, '靠离泊计划表.xls')
    },
    workbook2blob(workbook) {
      // 生成excel的配置项
      var wopts = {
        // 要生成的文件类型
        bookType: 'xlsx',
        // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: 'binary'
      }
      var wbout = XLSX.write(workbook, wopts)
      // 将字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
      const buf = s2ab(wbout)
      var blob = new Blob([buf], {
        type: 'application/octet-stream'
      })
      return blob
    },

    // 将blob对象 创建bloburl,然后用a标签实现弹出下载框
    openDownloadDialog(blob, fileName) {
      if (typeof blob === 'object' && blob instanceof Blob) {
        blob = URL.createObjectURL(blob) // 创建blob地址
      }
      var aLink = document.createElement('a')
      aLink.href = blob
      // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
      aLink.download = fileName || ''
      var event
      if (window.MouseEvent) event = new MouseEvent('click')
      //   移动端
      else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        )
      }
      aLink.dispatchEvent(event)
    },
    /**
     * tab切换
     */
    handleAcitveClick(tab) {
      if (tab.index === '0') {
        this.queryAll.activeName = 'first'
      } else if (tab.index === '1') {
        this.queryAll.activeName = 'second'
      } else if (tab.index === '2') {
        this.queryAll.activeName = 'third'
      } else if (tab.index === '3') {
        this.queryAll.activeName = 'fourth'
      }
      this.queryAll.startpage = 1
      this.queryAll.pagesize = 10
      this.getBoatDispatchList()
    },

    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getBoatDispatchList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getBoatDispatchList()
    },
    /**
     * 判断form表单是否更改
     */
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerInner) { // 详细数据
        oldV = this.detailFormData
        newV = this.$refs.boatBerth.formData
      }
      if (this.dynamicTracking) { // 动态跟踪
        oldV = this.dynamicFormData
        newV = this.$refs.dynamicTracking.formData
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        done()
      }
    },
    // 获取某天日期的下一天，默认为第二天 默认输出格式为yyyy-mm-dd
    getNextDate(date, day = 1, format = '{y}-{m}-{d}') {
      if (date) {
        date = date.match(/\d+/g).join('-'); // 格式为2022年09月19日处理
        const nDate = new Date(date);
        nDate.setDate(nDate.getDate() + day);

        const formatObj = {
          y: nDate.getFullYear(),
          m: nDate.getMonth() + 1,
          d: nDate.getDate()
        };
        return format.replace(/{([ymd])+}/g, (result, key) => {
          const value = formatObj[key];
          return value.toString().padStart(2, '0');
        });
      }
      console.log('date格式不正确');
    }
  }
}
</script>

<style lang="less" scoped>
@import "~@/assets/form.less";

.box {
  display: flex;
  justify-content: space-between;
  background: #ffffff;
	border: 1px solid #e1e4eb;
	border-radius: 4px 4px 0 0;
	border-top: none;
  .left {
    width: 260px;
    min-height: calc(100vh - 110px);
    border: 1px solid #e1e4eb;
    display: inline-block;
    white-space: nowrap;
    position: relative;
    transition: all 0.3s;
    &.close {
      width: 0px;

      .content {
        display: none;
      }
    }
    .content {
      overflow-x: hidden;
      height: 100%;
      .left-top {
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        background: rgb(245,247,250);
        font-size: 14px;
      }
      .shipData {
        width: 100%;
        height: 150px;
        margin-top:10px;
      }
      .panel {
        width: 100%;
        height: 200px;
      }
      .step {
        height: calc(100vh - 557px);
        padding: 20px;
        box-sizing: border-box;
      }
    }
    .fold-wrap {
      position: absolute;
      top: 0;
      right: -16px;
      width: 16px;
      height: 100%;
      background-color: #f5f7fa;
      display: inline-block;
    }

    .btn-fold {
      font-size: 12px;
      background-color: #f5f7fa;
      width: 16px;
      padding: 15px 0;
      position: absolute;
      top: 50%;
      right: 0px;
      transform: translateY(-50%);
      cursor: pointer;
      overflow: hidden;
      opacity: 0.8;
    }
    .btn-fold:hover {
      opacity: 1;
      // transform:scale(1.2);//设置缩放比例
      // transform: translateX(10%);
    }
  }
  .right {
    width: calc(100% - 270px);
    height: 100%;
  }
  .close + .right {
    width: calc(100% - 20px);
  }
}
/deep/ .el-step.is-vertical .el-step__line {
  width: 2px;
  top: 20px;
  bottom: -10px;
  left: 7px;
}
/deep/ .el-step__icon {
  width: 14px;
  height: 14px;
}
.selectBox {
	justify-content: space-between;
	display: flex;
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-bottom: 0;
	border-left: none;
	height: 50px;
	position: relative;
	align-items: center;
	padding-left: 14px;
	padding-right: 20px;
}
.input_box {
	display: flex;
}
.page {
	background: #ffffff;
	text-align: right;
	border-radius: 0 0 4px 4px;
	padding: 5px 20px;
}
/deep/.el-tabs--border-card > .el-tabs__content {
	padding: 0 !important;
}
//抽屉底部样式
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 16px;
	border-bottom: 1px solid gainsboro;
}
.demo-drawer__footer {
	text-align: right;
	padding-right: 20px;
	border-top: 1px solid #c8cfde;
	background-color: #f5f7fa;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	line-height: 50px;
}

</style>
